package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bean.User;
import bean.Userinfo;
import dao.CheckSellUserInfo;
import dao.SelectOneUser;
import dao.SelectOneUserinfo;
import dao.UpdateUser;

/**
 * Servlet implementation class UserUpdateServlet
 */
public class UserUpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserUpdateServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		String userphoneString = new String(request.getParameter("userphone")
				.getBytes("iso-8859-1"), "UTF-8");
		String userinfoString = new String(request.getParameter("userinfo")
				.getBytes("iso-8859-1"), "UTF-8");

		HttpServletRequest httpServletRequest = request;
		HttpSession session = httpServletRequest.getSession();
		String numString = (String) session.getAttribute("usernum");// 取得session中得字段信息

		if (CheckSellUserInfo.checkInfo(numString)) {
			UpdateUser.update(userphoneString, userinfoString, numString);
			User user = SelectOneUser.getOneUser(numString);
			request.setAttribute("user", user);
			request.getRequestDispatcher("/user/user.jsp").forward(request,
					response);
			return;
		}

		Userinfo userinfo;
		userinfo = SelectOneUserinfo.getUserinfo(numString);
		UpdateUser.insert(userphoneString, userinfoString, userinfo);
		User user = SelectOneUser.getOneUser(numString);
		request.setAttribute("user", user);
		request.getRequestDispatcher("/user/user.jsp").forward(request,
				response);
		return;
	}

}
